<?php
/**
 * Create by PhpStorm
 * User: mozongyou
 * Date: 2021/8/13
 * Time: 5:03 下午
 */
/**
 * 基础控制器
 * ${PARAM_DOC}
 * @return ${TYPE_HINT}
 * ${THROWS_DOC}
 * @author mozongyou
 * @date 2021-08-13 5:03 下午
 */
declare(strict_types=1);

namespace App\Controller;

use App\Exception\GeneralException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;

class BaseController extends AbstractController
{

    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * 字段验证器
     * @param array $rule
     * @param array $messages
     * @author mozongyou
     * @date 2021-09-30 5:18 下午
     */
    protected function validatorAll($rule = [], $messages = [])
    {
        $validator = $this->validationFactory->make($this->request->all(), $rule, $messages);
        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            throw new GeneralException($errorMessage, 0);
        }

    }

    /**
     * 成功的 返回结构
     * @param null $data
     * @param string $msg
     * @return \Psr\Http\Message\ResponseInterface
     * @author mozongyou
     * @date 2021-08-13 5:09 下午
     */
    protected function success($data = null, $msg = '成功')
    {
        $result = [
            'code' => 1,
            'msg' => $msg,
            'response' => $data
        ];
        return $this->response->json($result);
    }

    /**
     * 失败的 返回结构
     * @param string $msg
     * @param int $code
     * @param null $data
     * @return \Psr\Http\Message\ResponseInterface
     * @author mozongyou
     * @date 2021-08-13 5:11 下午
     */
    protected function error($msg = '失败', $code = 0, $data = null)
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'response' => $data
        ];
        return $this->response->json($result);
    }


}